// pages/ordermsg/ordermsg.js
var app = getApp();
var url = app.globalData.url;
var userId;
var openId;
var user;
var tempFilePaths = [];
var comment_img = [];
var uploadUrl = url + '/api/other/upload_comment';
var m_star = 0;
var w_star = 0;
var f_star = 0;
var finish = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    URL: app.globalData.url,
    path:'/images/star_end.png',
    starY:0,
    starE: 0,
    starS: 0,
    shipping:{},
    order_sn:'',
    goods_price:'',
    goods_list:[],
    add_time:'',
    paytype:'待支付',
    order_id:0,
    image:[],
    hide:'hide',
    comment_goods_img:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    userId = wx.getStorageSync('user_id');
    openId = wx.getStorageSync('open_id');
    user = wx.getStorageSync('user');
    wx.setNavigationBarTitle({
      title: '订单详情'
    })
    console.log(getCurrentPages());
    // console.log(options.order_id);
    var that = this;
    var address = '';
    wx.request({
      url: url + '/api/user/order_detail',
      method:"POST",
      data:{
        order_id: options.order_id,
        user_id: userId,
      },
      success:function(res){
        console.log(res);
        var orderInfo = res.data.order_info;
        if (orderInfo.user_note == ""){
          orderInfo.user_note = "暂无留言信息";
        }
        for (var i in res.data.region_list){
          // console.log(res.data.region_list[i]);
          address += res.data.region_list[i]+' ';
        }
        // console.log(address);
        that.setData({
          shipping:{
            address: address + orderInfo.address,
            consignee: orderInfo.consignee,
            shipping_name: orderInfo.shipping_name,
            shipping_price: orderInfo.shipping_price,
            mobile: orderInfo.mobile,
          },
          goods_info: orderInfo,
          goods_list: orderInfo.goods_list,
          order_sn: orderInfo.order_sn,
          goods_price: orderInfo.order_amount,
          add_time: orderInfo.add_time,
          user_note: orderInfo.user_note,
          order_id: options.order_id,
          paytype: orderInfo.order_status_desc,
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  submit_payment: function (o) {
    console.log(o.currentTarget.dataset.order_id);
    // console.log(openId);

    wx.request({
      url: url + '/api/payment/getxcxPay',
      data: {
        openid: openId,
        // user_id:userId,
        pay_radio: 'pay_code=weixinsmall',
        order_id: o.currentTarget.dataset.order_id,
      },
      success: function (res) {
        // console.log(res.data.timeStamp);
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': 'prepay_id=' + res.data.package,
          'signType': 'MD5',
          'paySign': res.data.paySign,
          'success': function (res) {
            wx.reLaunch({
              url: '/pages/user/user',
            })
          },
          'fail': function (res) {
            console.log(res);
            wx.showToast({
              title: '已取消支付',
              icon: 'success',
              duration: 2000
            })
          }
        })
      }
    });
  },
 /**
 * 确认收货
 */
  confireTake: function (c) {
    // console.log(c.currentTarget.dataset.order_id)
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认收货',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: url + '/api/user/order_confirm',
            method: 'POST',
            data: {
              order_id: c.currentTarget.dataset.order_id,
              user_id: userId,
            },
            success: function (res) {
              console.log(res);
              if (res.data.code == 200) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    var address = '';
                    wx.request({
                      url: url + '/api/user/order_detail',
                      method: "POST",
                      data: {
                        order_id: c.currentTarget.dataset.order_id,
                        user_id: userId,
                      },
                      success: function (res) {
                        console.log(res);
                        var orderInfo = res.data.order_info;
                        if (orderInfo.user_note == "") {
                          orderInfo.user_note = "暂无留言信息";
                        }
                        for (var i in res.data.region_list) {
                          // console.log(res.data.region_list[i]);
                          address += res.data.region_list[i] + ' ';
                        }
                        // console.log(address);
                        that.setData({
                          shipping: {
                            address: address + orderInfo.address,
                            consignee: orderInfo.consignee,
                            shipping_name: orderInfo.shipping_name,
                            shipping_price: orderInfo.shipping_price,
                            mobile: orderInfo.mobile,
                          },
                          goods_info: orderInfo,
                          goods_list: orderInfo.goods_list,
                          order_sn: orderInfo.order_sn,
                          goods_price: orderInfo.order_amount,
                          add_time: orderInfo.add_time,
                          user_note: orderInfo.user_note,
                          order_id: c.currentTarget.dataset.order_id,
                          paytype: orderInfo.order_status_desc,
                        });
                      }
                    })
                  }
                })
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 选择上传的图片
   */
  uploadImg:function(){
    var that = this;
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log(res.tempFilePaths);
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        tempFilePaths = res.tempFilePaths
        that.setData({
          image: tempFilePaths,
        })
      }
    })
  },
  /**
   * 删除图片
   */
  closeImg:function(o){
    var that = this;
    // console.log(o.currentTarget.dataset.key);
    tempFilePaths.splice(o.currentTarget.dataset.key,1);
    console.log(tempFilePaths);
    that.setData({
      image: tempFilePaths,
    })
  },
  /**
   * 商品星级评价
   */
  RepresentStar:function(e){
    console.log(e)
    if (e.detail.x > 176 && e.detail.x < 205 && e.detail.y < 36 && e.detail.y > 17){
      m_star = 1;
      this.setData({
        starY: 0.2,
      })
    } else if (e.detail.x > 205 && e.detail.x < 233 && e.detail.y < 36 && e.detail.y > 17){
      m_star = 2;
      this.setData({
        starY: 0.4,
      })
    } else if (e.detail.x > 233 && e.detail.x < 261 && e.detail.y < 36 && e.detail.y > 17) {
      m_star = 3;
      this.setData({
        starY: 0.6,
      })
    } else if (e.detail.x > 261 && e.detail.x < 287 && e.detail.y < 36 && e.detail.y > 17) {
      m_star = 4;
      this.setData({
        starY: 0.8,
      })
    } else if (e.detail.x > 287 && e.detail.x < 303 && e.detail.y < 36 && e.detail.y > 17) {
      m_star = 5;
      this.setData({
        starY: 1,
      })
    }
  },
  /**
   * 物流星级评价
   */
  ShippingStar:function(e){
    console.log(e)
    if (e.detail.x > 176 && e.detail.x < 205 && e.detail.y < 58 && e.detail.y > 45) {
      w_star = 1;
      this.setData({
        starE: 0.2,
      })
    } else if (e.detail.x > 205 && e.detail.x < 233 && e.detail.y < 58 && e.detail.y > 45) {
      w_star = 2;
      this.setData({
        starE: 0.4,
      })
    } else if (e.detail.x > 232 && e.detail.x < 261 && e.detail.y < 58 && e.detail.y > 45) {
      w_star = 3;
      this.setData({
        starE: 0.6,
      })
    } else if (e.detail.x > 260 && e.detail.x < 287 && e.detail.y < 58 && e.detail.y > 45) {
      w_star = 4;
      this.setData({
        starE: 0.8,
      })
    } else if (e.detail.x > 286 && e.detail.x < 303 && e.detail.y < 58 && e.detail.y > 45) {
      w_star = 5;
      this.setData({
        starE: 1,
      })
    }
  },
  /**
   * 服务星级评价
   */
  ServiceStar: function (e) {
    console.log(e)
    if (e.detail.x > 176 && e.detail.x < 205 && e.detail.y < 85 && e.detail.y > 68) {
      f_star = 1;
      this.setData({
        starS: 0.2,
      })
    } else if (e.detail.x > 205 && e.detail.x < 233 && e.detail.y < 85 && e.detail.y > 68) {
      f_star = 2;
      this.setData({
        starS: 0.4,
      })
    } else if (e.detail.x > 232 && e.detail.x < 261 && e.detail.y < 85 && e.detail.y > 68) {
      f_star = 3;
      this.setData({
        starS: 0.6,
      })
    } else if (e.detail.x > 260 && e.detail.x < 287 && e.detail.y < 85 && e.detail.y > 68) {
      f_star = 4;
      this.setData({
        starS: 0.8,
      })
    } else if (e.detail.x > 286 && e.detail.x < 303 && e.detail.y < 85 && e.detail.y > 68) {
      f_star = 5;
      this.setData({
        starS: 1,
      })
    }
  },
  /**
   * 提交评论
   */
  CommentSubmit: function (e) {
    console.log(e.currentTarget.dataset.goods_id);
    var that = this;
    // console.log(tempFilePaths.length);return false;
    if (m_star == 0 || w_star == 0 || f_star == 0) {
      wx.showToast({
        title: '请评分',
        icon: 'success',
        duration: 2000
      })
      return false;
    }


    var successUp = 0;
    var failUp = 0;
    var i = 0;
    var length = tempFilePaths.length;
    var order_id = e.currentTarget.dataset.order_id;
    var goods_id = e.currentTarget.dataset.goods_id;
    var content = e.detail.value.content;
    var is_anonymity = e.detail.value.is_anonymity[0];
    if (tempFilePaths.length > 0){
      this.uploadDIY(tempFilePaths, successUp, failUp, i, length, order_id, goods_id, content, is_anonymity);
    }else{
      wx.request({
        url: url + '/api/user/add_comment',
        method: 'POST',
        data: {
          user: user,
          order_id: order_id,
          goods_id: goods_id,
          content: content,
          hide_username: is_anonymity,//是否匿名
          service_rank: f_star,
          deliver_rank: w_star,
          goods_rank: m_star,
        },
        success: function (res) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success',
            duration: 2000,
          })
          // console.log(res);
          if (res.data.status == 200) {
            that.setData({
              hide: 'hide',
            })
          }
        }
      })
    }
    // console.log(finish);
    // console.log(e);
  },
  /* 函数描述：作为上传文件时递归上传的函数体体；
 * 参数描述： 
 * filePaths是文件路径数组
 * successUp是成功上传的个数
 * failUp是上传失败的个数
 * i是文件路径数组的指标
 * length是文件路径数组的长度
 */
  uploadDIY(filePaths, successUp, failUp, i, length, c_order_id, c_goods_id, c_content, c_is_anonymity) {
    // console.log(filePaths[i]+','+i);
    var that = this;
    wx.uploadFile({
      url: uploadUrl,
      filePath: filePaths[i],
      name: 'comment_img_file',
      formData: null,
      success: (resp) => {
        // console.log(resp.data);
        comment_img.push(resp.data);
        successUp++;
      },
      fail: (res) => {
        failUp++;
      },
      complete: () => {
        i++;
        if (i == length) {
          // wx.showToast({
          //   title: '总共' + successUp + '张上传成功,' + failUp + '张上传失败！',
          //   icon:'success',
          //   duration: 2000,
          // });
          wx.hideLoading()
              wx.request({
                url: url + '/api/user/add_comment',
                method:'POST',
                data:{
                  user:user,
                  order_id: c_order_id,
                  goods_id: c_goods_id,
                  content: c_content,
                  hide_username: c_is_anonymity,//是否匿名
                  service_rank:f_star,
                  deliver_rank:w_star,
                  goods_rank:m_star,
                  comment_img: comment_img,
                },
                success:function(res){
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'success',
                    duration: 2000,
                  })
                  // console.log(res);
                  if (res.data.status == 200){
                    that.setData({
                      hide:'hide',
                    })
                  }
                }
              })
        }
        else {  //递归调用uploadDIY函数
          wx.showLoading({
            title:'图片上传中...',
            mask:true,
          })
          this.uploadDIY(filePaths, successUp, failUp, i, length, c_order_id, c_goods_id, c_content, c_is_anonymity);
        }
      },
    });

    return comment_img;
  },
  /**
   * 点击显示评论层
   */
  clickComment:function(e){
    var that = this;
    wx.request({
      url: url + '/api/user/add_comment',
      data: {
        rec_id: e.currentTarget.dataset.rec_id,
      },
      success: function (info) {
        console.log(info)
        that.setData({
          comment_goods_id: info.data.order_goods.goods_id,
          comment_goods_img: info.data.order_goods.original_img,
          hide: '',
        })
        
      }
    })
  },
  /**
   * 再次购买
   */
  buy_again:function(g){
    console.log(g.currentTarget.dataset.goods_id);
    wx.redirectTo({
      url: '/pages/goodsInfo/goodsInfo?id=' + g.currentTarget.dataset.goods_id,
    })
  },
  checkShipping:function(e){
    wx.navigateTo({
      url: '/pages/shipping/shipping?order_id= ' + e.currentTarget.dataset.order_id,
    })
  }
})